﻿using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace Mrb.Utils
{
    public static class JsonExtensions
    {
        public static T ParseJsonObject<T>(this string jsonString)
            where T : IFromJson, new()
        {
            var t = new T();
            var jToken = JObject.Parse(jsonString);
            t.FromJson(jToken);
            return t;
        }

        public static IDictionary<string, string> ParseJsonDictionary(this string jsonString)
        {
            var dictionary = new Dictionary<string, string>();
            var jToken = JObject.Parse(jsonString);
            foreach (JProperty property in jToken.Children())
            {
                if (property.Value.Type == JsonTokenType.String)
                {
                    dictionary[property.Name] = property.Value.Value<string>();
                }
                else
                {
                    dictionary[property.Name] = property.Value.ToString();
                }
            }
            return dictionary;
        }
    }
}